package com.example.chengww.myone.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.chengww.myone.R;
import com.example.chengww.myone.activity.MainActivity;
import com.example.chengww.myone.activity.ReadADContentActivity;
import com.example.chengww.myone.activity.ReadEssayActivity;
import com.example.chengww.myone.adapter.MyPagerAdapter;
import com.example.chengww.myone.adapter.MyReadContentAdapter;
import com.example.chengww.myone.anim.FrameAnimation;
import com.example.chengww.myone.bean.Constants;
import com.example.chengww.myone.bean.Read;
import com.example.chengww.myone.bean.ReadAd;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class ReadFragment extends LazyFragment implements View.OnClickListener,AdapterView.OnItemClickListener{

    // 标志位，标志已经初始化完成。
    private boolean isPrepared;
    private RelativeLayout relativeLayout;
    private ViewPager viewPager,readViewPager;
    private Context context;
    private MyPagerAdapter pagerAdapter;
    private List<View> views;
    //轮播圆点
    private LinearLayout readLayoutPoint;
    private List<ReadAd.Data> readADs;
    //阅读内容
    private List<Read.Data.Essay> essay;
    private List<Read.Data.Serial> serial;
    private List<Read.Data.Question> question;
    //轮播runnable
    private MyRunnable myRunnable = new MyRunnable();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 10086){
                if (views == null || views.size() == 0){
                    readADs = (List<ReadAd.Data>) msg.obj;
                    views = new ArrayList<>();
                    for (int i = 0; i < readADs.size(); i++) {
                        ImageView image = new ImageView(context);
                        image.setId(readADs.get(i).getId());
                        Picasso.with(context).load(readADs.get(i).getCover()).config(Bitmap.Config.RGB_565)
                                .placeholder(R.mipmap.default_hp_image).into(image);
                        //点击监听
                        image.setOnClickListener(ReadFragment.this);
                        views.add(image);
                        //圆点
                        ImageView imagePoint = new ImageView(context);
                        imagePoint.setPadding(15,0,15,0);
                        readLayoutPoint.addView(imagePoint);

                        if (i == 0){
                            imagePoint.setImageResource(R.drawable.guide_checked_index);
                        }else {
                            imagePoint.setImageResource(R.drawable.guide_default_index);
                        }
                    }
                    pagerAdapter = new MyPagerAdapter(views);
                    viewPager.setAdapter(pagerAdapter);
                }

            }else if (msg.what == 10087){
                //轮播
                if (views != null && views.size() != 0){
                    handler.postDelayed(myRunnable,6000);
                }
            }else if (msg.what == 10088){
                //停止轮播
                handler.removeCallbacks(myRunnable);
            }else if (msg.what == 10089){
                //内容加载
                Read read = (Read) msg.obj;
                essay = read.getData().getEssay();
                serial = read.getData().getSerial();
                question = read.getData().getQuestion();
                //listView

                List<View> views = new ArrayList<>();
                for (int i = 0; i < essay.size(); i++) {
                    ListView listView = new ListView(context);
                    MyReadContentAdapter adapter = new MyReadContentAdapter(
                            essay,serial,question,context,i);
                    listView.setAdapter(adapter);
                    listView.setDivider(null);
                    listView.setVerticalScrollBarEnabled(false);
                    listView.setOnItemClickListener(ReadFragment.this);
                    listView.setBackgroundResource(R.drawable.relative_background);
                    views.add(listView);
                }
                //viewPager
                MyPagerAdapter pagerAdapter = new MyPagerAdapter(views);
                readViewPager.setAdapter(pagerAdapter);
            }
        }
    };

    public ReadFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        relativeLayout = (RelativeLayout) inflater.inflate(
                R.layout.fragment_read, container, false);
        viewPager = (ViewPager) relativeLayout.findViewById(R.id.read_ad);
        readViewPager = (ViewPager) relativeLayout.findViewById(R.id.read_content_pager);
        readLayoutPoint = (LinearLayout) relativeLayout.findViewById(R.id.readLayoutPoint);
        ((MainActivity)context).setHandler(handler);
        isPrepared = true;
        lazyLoad();
        return relativeLayout;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //点击事件
        viewPager.setOnClickListener(this);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                //关联引导页和圆点状态
                for (int i = 0; i < views.size(); i++) {
                    ImageView imagePoint = (ImageView) readLayoutPoint.getChildAt(i);
                    if (i == position){
                        imagePoint.setImageResource(R.drawable.guide_checked_index);
                    }else {
                        imagePoint.setImageResource(R.drawable.guide_default_index);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        if (v instanceof ImageView){
            Intent intent = new Intent(context, ReadADContentActivity.class);
            ReadAd.Data data = readADs.get(viewPager.getCurrentItem());
            intent.putExtra("id", data.getId());
            intent.putExtra("title",data.getTitle());
            intent.putExtra("bottom_text",data.getBottom_text());
            intent.putExtra("cover",data.getCover());
            intent.putExtra("bgcolor",data.getBgcolor());
            startActivity(intent);
            ((MainActivity)context).overridePendingTransition(R.anim.activity_in,R.anim.activity_out);
        }
    }

    @Override
    protected void lazyLoad() {
        if(!isPrepared || !isVisible) {
            return;
        }
        //填充各控件的数据

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(context, ReadEssayActivity.class);
        //viewpager位置
        int pos = readViewPager.getCurrentItem();
        String essayId = null;
        boolean hasRadio = false;
        switch (position){
            case 0:
                essayId = essay.get(pos).getContent_id();
                hasRadio = essay.get(pos).isHas_audio();
                break;
            case 1:
                essayId = serial.get(pos).getId();
                hasRadio = serial.get(pos).isHas_audio();
                break;
            case 2:
                essayId =question.get(pos).getQuestion_id();
                hasRadio = false;
                break;
        }
        intent.putExtra("id",essayId);
        intent.putExtra("radio",hasRadio);
        intent.putExtra("type",position);
        startActivity(intent);
        ((MainActivity)context).overridePendingTransition(R.anim.activity_in,R.anim.activity_out);
    }


    /**
     * 内部类，handler post此runnable，实现循环
     */
    class MyRunnable implements Runnable{

        @Override
        public void run() {
            int pos = viewPager.getCurrentItem();
            viewPager.setCurrentItem((pos+1)%views.size(),false);
            handler.postDelayed(this,6000);
        }
    }
}
